// 引入mysql的配置文件
const db = require('../config/db');
const {
    DataTypes,
    Deferrable
} = require("sequelize");
const uuid = require('node-uuid');
// 引入sequelize对象
const Sequelize = db.sequelize;
// 引入数据表模型
const category = require('../schema/category.js')(Sequelize, DataTypes);
const article = require('../schema/article')(Sequelize, DataTypes, Deferrable, category);
// category.hasMany(article, {
//     foreignKey: 'category_id'
// });
article.sync({
    alter: true
}); //自动创建表

class articleModel {
    /**
     * 创建学生表模型
     * @param data
     * @returns {Promise<*>}
     */
    static async create(data) {
        return await article.create({
            articleTitle: data.articleTitle,
            articleContent: data.articleContent,
            categoryId: data.categoryId,
            id: uuid.v1()
        });
    }

    /**
     * 查询全部菜单
     * @param  {}
     * @returns {Promise<Model>}
     */
    static async getArticle() {
        let result=await Sequelize.query(`SELECT
        a.id,
        a.article_title articleTitle,
        a.category_id categoryId,
        a.article_content articleContent,
        a.create_time createTime,
        a.update_time updateTime,
        c. NAME categoryName
        FROM
            article a,
            category c
        WHERE
        a.category_id = c.id and a.is_delete=0`);
        return result[0]
    }

    /**
     * 删除菜单
     * @param {*} id 
     * @returns 
     */
    static async deleteCategory(id) {
        return await article.destroy({
            where: {
                id
            }
        })
    }
    /**
     * 查询学生信息的详情
     * @param id 学生信息ID
     * @returns {Promise<Model>}
     */
    static async getCategoryDetail(query) {
        return await article.findOne({
            where: {
                ...query
            }
        });
    }
}

module.exports = articleModel;